package ru.resumeService.web.filter;

import ru.resumeService.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class FilterLogin implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String logout = servletRequest.getParameter("logout");
        HttpSession session = ((HttpServletRequest) servletRequest).getSession();
        RequestDispatcher dispatcher;
        Boolean isLogin = (Boolean) session.getAttribute("isLogin");
        if (isLogin && logout == null) {
            dispatcher = servletRequest.getRequestDispatcher("/resumeList");
        } else if (logout != null && logout.equals("true")) {
            session.invalidate();
            dispatcher = servletRequest.getRequestDispatcher("/index.jsp");
        } else {
            session.invalidate();
            servletRequest.setAttribute("message", "Введены не верные данные!");
            dispatcher = servletRequest.getRequestDispatcher("/index.jsp");
        }
        if (dispatcher != null) {
            try {
                dispatcher.forward(servletRequest, servletResponse);
            } catch (ServletException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }

    }

    @Override
    public void destroy() {
        //To change body of implemented methods use File | Settings | File Templates.
    }
}
